package com.gomore.opple.module.main.shoppingcar;

import android.support.v7.widget.LinearLayoutManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.gomore.opple.R;
import com.gomore.opple.model.EventDeleteShoppingCar;
import com.gomore.opple.model.EventQueryShoppingCar;
import com.gomore.opple.model.EventReflashShoppingCar;
import com.gomore.opple.model.Good;
import com.gomore.opple.module.BaseFragmentV4;
import com.gomore.opple.module.IntentStart;
import com.gomore.opple.module.main.shoppingcar.adapter.ShoppingCarAdapter;
import com.gomore.opple.service.SelectAllClickListener;
import com.gomore.opple.utils.BigDecimalUtils;
import com.gomore.opple.utils.DialogUtils;
import com.gomore.opple.web.cgform.shopcart.entity.TOShopcartEntity;
import com.gomore.opple.widgets.PullRecyclerView;
import com.gomore.opple.widgets.dialog.ConfirmDialog;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;

/**
 * Created by asus on 2017/5/9.
 */
public class ShoppingCarFragment extends BaseFragmentV4 implements ShoppingCarContract.View, SelectAllClickListener {

    @Bind(R.id.recyclerView)
    PullRecyclerView recyclerView;
    @Bind(R.id.empty_view)
    View empty_view;
    @Bind(R.id.select_all_linear)
    LinearLayout select_all_linear;
    @Bind(R.id.select_all)
    CheckBox select_all;
    @Bind(R.id.delete)
    TextView delete;
    @Bind(R.id.total_text)
    TextView total_text;
    @Bind(R.id.total_number)
    TextView total_number;
    @Bind(R.id.precent_edittext)
    EditText precent_edittext;
    @Bind(R.id.go_to_cash)
    LinearLayout go_to_cash;

    private ShoppingCarContract.Presenter mPresenter;
    private ShoppingCarAdapter shoppingCarAdapter;
    private BigDecimal total;
    private BigDecimal lowestPrecent;
    private BigDecimal inputPresent;

    public static ShoppingCarFragment getInstance() {
        return new ShoppingCarFragment();
    }

    @Override
    protected void initalizeData() {
        super.initalizeData();
        EventBus.getDefault().register(this);
        total = new BigDecimal(0);
    }

    @Override
    protected void initalizeViews() {
        super.initalizeViews();
        recyclerView.setCanPullUp(false);
        recyclerView.setCanPullDown(false);
        if (mPresenter.getUser().getLowestDiscount() == null) {
            lowestPrecent = new BigDecimal(100);
        } else {
            lowestPrecent = mPresenter.getUser().getLowestDiscount();
        }
        shoppingCarAdapter = new ShoppingCarAdapter(getActivity(), getActivity(), R.layout.shopping_car_item, mPresenter.getShoppingCarData(), lowestPrecent);
        recyclerView.setLayoutManager(new LinearLayoutManager(ShoppingCarFragment.this.getActivity()));
        recyclerView.setAdapter(shoppingCarAdapter);
        shoppingCarAdapter.setAllClickListener(this);
        if (mPresenter.getConsumer() != null && mPresenter.getConsumer().getId() != null) {
            mPresenter.queryShoppingCar(mPresenter.getConsumer().getId());
        } else {
            showContentView();
        }

        precent_edittext.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String str = s.toString().trim();
                BigDecimal totalBigDecimal = total;
                if (!TextUtils.isEmpty(str)) {
                    if (str.startsWith("0")) {
                        precent_edittext.setText("");
                        return;
                    }
                    if (str.length() > 2) {
                        str = str.substring(0, 2);
                        precent_edittext.setText(str);
                        precent_edittext.setSelection(2);
                    }
                    //折扣比率
                    inputPresent = new BigDecimal(str);
                    totalBigDecimal = inputPresent.multiply(totalBigDecimal).divide(new BigDecimal(100));
                    total_text.setText("¥" + totalBigDecimal.toString());
                } else {
                    //折扣比率置为空
                    inputPresent = null;
                    total_text.setText("¥" + totalBigDecimal.toString());
                }
            }
        });
    }

    @Override
    protected int getLayoutView() {
        return R.layout.fragment_shopping_car;
    }

    @Override
    public void showProgressDialog() {
        DialogUtils.showLoadingDialog(getActivity(), getResources().getString(R.string.loading));
    }

    @Override
    public void hideProgressDialog() {
        DialogUtils.closeLoadingDialog();
    }

    @Override
    public void showMessage(String msg) {
        showToast(msg);
    }

    @Override
    public void showMessage(int msgId) {
        showToast(msgId);
    }

    /**
     * 加载完毕
     */
    @Override
    public void showLoadMoreCompleted() {
        recyclerView.onFooterRefreshComplete();
    }

    /**
     * 刷新完毕
     */
    @Override
    public void showRefreshCompleted() {
        recyclerView.onHeaderRefreshComplete();
    }

    @Override
    public void showContentView() {
        shoppingCarAdapter = new ShoppingCarAdapter(getActivity(), getActivity(), R.layout.shopping_car_item, mPresenter.getShoppingCarData(), lowestPrecent);
        recyclerView.setLayoutManager(new LinearLayoutManager(ShoppingCarFragment.this.getActivity()));
        recyclerView.setAdapter(shoppingCarAdapter);
        shoppingCarAdapter.setAllClickListener(this);
        if (mPresenter.getShoppingCarData().size() == 0) {
            recyclerView.setVisibility(View.GONE);
            select_all_linear.setVisibility(View.GONE);
            delete.setVisibility(View.GONE);
            empty_view.setVisibility(View.VISIBLE);
        } else {
            recyclerView.setVisibility(View.VISIBLE);
            select_all_linear.setVisibility(View.VISIBLE);
            delete.setVisibility(View.VISIBLE);
            empty_view.setVisibility(View.GONE);
            //将状态置为初始化
            select_all.setChecked(false);
            showTotal(new BigDecimal(0), 0, true);
        }
    }

    @Override
    public void showTotal(BigDecimal bigDecimal, int size, boolean clearDiscountEditText) {
        total = bigDecimal;
        //清空输入的折扣
        if (clearDiscountEditText) {
            precent_edittext.setText("");
        }
        if (inputPresent != null) {
            bigDecimal = inputPresent.multiply(bigDecimal).divide(new BigDecimal(100));
        }
        total_text.setText("¥" + BigDecimalUtils.forMate(bigDecimal).toString());
        total_number.setText("(" + size + ")");
    }

    @Override
    public void selectAllView() {
        if (!select_all.isChecked()) {
            shoppingCarAdapter.initDate();
            shoppingCarAdapter.notifyDataSetChanged();
        } else {
            shoppingCarAdapter.initDateToCheck();
            shoppingCarAdapter.notifyDataSetChanged();
        }
        //显示合计
        mPresenter.getTotal(mPresenter.getShoppingCarData(), ShoppingCarAdapter.getIsSelected());
    }

    @Override
    public int getGoodNumber(List<TOShopcartEntity> toShopcartEntityLists) {
        int number = 0;
        for (int i = 0; i < toShopcartEntityLists.size(); i++) {
            if (toShopcartEntityLists.get(i) != null) {
                number = number + toShopcartEntityLists.get(i).getGoodsNum();
            }
        }
        return number;
    }

    @Override
    public void setPresenter(ShoppingCarContract.Presenter presenter) {
        mPresenter = presenter;
    }

    @Override
    public void SelectAll() {
        //判断是否全选了
        int size = mPresenter.getShoppingCarData().size();
        //显示全选按钮
        if (getSize(size) == size) {
            select_all.setChecked(true);
        } else {
            select_all.setChecked(false);
        }
        //显示合计
        mPresenter.getTotal(mPresenter.getShoppingCarData(), ShoppingCarAdapter.getIsSelected());
    }

    @Override
    public void updateCostPrice(String cartId, String costPrice, String goodsId, String goodsNum, boolean isReflashShoppingCar) {
        if (cartId != null && costPrice != null && goodsId != null && goodsNum != null) {
            mPresenter.updateCostPrice(cartId, costPrice, goodsId, goodsNum, isReflashShoppingCar);
        }
    }

    private int getSize(int size) {
        int total = 0;
        for (int i = 0; i < size; i++) {
            if (ShoppingCarAdapter.getIsSelected().get(i)) {
                total++;
            }
        }
        return total;
    }

    @OnClick({R.id.select_all, R.id.delete, R.id.go_to_cash})
    public void onCLick(View view) {
        switch (view.getId()) {
            case R.id.select_all:
                selectAllView();
                break;
            case R.id.delete:
                final List<String> stringList = new ArrayList<>();
                for (int i = 0; i < ShoppingCarAdapter.getIsSelected().size(); i++) {
                    if (ShoppingCarAdapter.getIsSelected().get(i)) {
                        stringList.add(mPresenter.getShoppingCarData().get(i).getId());
                    }
                }
                if (stringList.size() == 0) {
                    showMessage("请选择要删除的商品");
                    return;
                }
                //确定框
                ConfirmDialog.onNoOnclickListener onNoOnclickListener = null;
                ConfirmDialog.onYesOnclickListener onYesOnclickListener = null;
                final String title = "提示";
                String message = "确定要删除吗?";
                onYesOnclickListener = new ConfirmDialog.onYesOnclickListener() {
                    @Override
                    public void onYesClick() {
                        mPresenter.deleteShoppingCar(stringList);
                    }
                };
                onNoOnclickListener = new ConfirmDialog.onNoOnclickListener() {
                    @Override
                    public void onNoClick() {
                        DialogUtils.cancel();
                    }
                };
                DialogUtils.showConfirmDialog(getActivity(), onYesOnclickListener, onNoOnclickListener, title, message);
                break;
            case R.id.go_to_cash:
                if (inputPresent != null) {
                    int com = inputPresent.compareTo(lowestPrecent);
                    if (com == -1) {
                        showMessage(R.string.no_promission);
                        return;
                    }
                }
                int goodsnumber = 0;
                final List<TOShopcartEntity> toShopcartEntities = new ArrayList<>();
                for (int i = 0; i < ShoppingCarAdapter.getIsSelected().size(); i++) {
                    if (ShoppingCarAdapter.getIsSelected().get(i)) {
                        toShopcartEntities.add(mPresenter.getShoppingCarData().get(i));
                        goodsnumber = goodsnumber + mPresenter.getShoppingCarData().get(i).getGoodsNum();
                    }
                }
                if (toShopcartEntities.size() == 0) {
                    showMessage(R.string.please_select_good);
                    return;
                }
                //确定框
                ConfirmDialog.onNoOnclickListener onNoOnclickListener1 = null;
                ConfirmDialog.onYesOnclickListener onYesOnclickListener1 = null;
                final String title1 = "提示";
                String message1 = "确定去结算吗?";
                final int finalGoodsnumber = goodsnumber;
                onYesOnclickListener1 = new ConfirmDialog.onYesOnclickListener() {
                    @Override
                    public void onYesClick() {
                        Good good = new Good();
                        if (inputPresent == null) {
                            good.setInputPresent(new BigDecimal(100));
                        } else {
                            good.setInputPresent(inputPresent);
                        }
                        good.setTotal(total);
                        good.setNumber(finalGoodsnumber);
                        good.setToShopcartEntities(toShopcartEntities);
                        IntentStart.getInstance().startAccountActivity(getActivity(), good);
                    }
                };
                onNoOnclickListener1 = new ConfirmDialog.onNoOnclickListener() {
                    @Override
                    public void onNoClick() {
                        DialogUtils.cancel();
                    }
                };
                DialogUtils.showConfirmDialog(getActivity(), onYesOnclickListener1, onNoOnclickListener1, title1, message1);
                break;
        }
    }

    public void onEventMainThread(EventQueryShoppingCar eventQueryShoppingCar) {
        if (eventQueryShoppingCar != null && eventQueryShoppingCar.isGetShoppingCar()) {
            if (mPresenter.getConsumer() == null) {
                mPresenter.getShoppingCarData().clear();
                showContentView();
            } else {
                mPresenter.queryShoppingCar(mPresenter.getConsumer().getId());
            }
        }
    }

    public void onEventMainThread(EventDeleteShoppingCar eventDeleteShoppingCar) {
        if (eventDeleteShoppingCar != null && eventDeleteShoppingCar.isDeteteShoppingCar()) {
            final List<String> stringList = new ArrayList<>();
            for (int i = 0; i < ShoppingCarAdapter.getIsSelected().size(); i++) {
                if (ShoppingCarAdapter.getIsSelected().get(i)) {
                    stringList.add(mPresenter.getShoppingCarData().get(i).getId());
                }
            }
            if (stringList.size() > 0) {
                mPresenter.deleteShoppingCar(stringList);
            }
        }
    }

    public void onEventMainThread(EventReflashShoppingCar eventReflashShoppingCar) {
        if (eventReflashShoppingCar != null && eventReflashShoppingCar.isReflashShoppingCar()) {
            mPresenter.queryShoppingCar(mPresenter.getConsumer().getId());
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
